﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using InvoiceChecking.Data.SqlClient;
using InvoiceChecking.Entities;

namespace Arch
{
    public static class GlobalUtilities
    {
        public static TList<T> SelectDistinctFromList<T>(TList<T> originalList, Enum[] distinctProperties) where T : IEntity, new()
        {
            Type instanceType = originalList.GetType().GetGenericArguments()[0].BaseType;

            PropertyInfo[] propertyColumns = new PropertyInfo[distinctProperties.Length];
            for (int i = 0; i < distinctProperties.Length; i++)
            {
                propertyColumns[i] = instanceType.GetProperty(distinctProperties[i].ToString());
            }

            TList<T> resultList = new TList<T>();
            StringCollection keys = new StringCollection();
            foreach (T instance in originalList)
            {
                string key = string.Empty;
                foreach (PropertyInfo pi in propertyColumns)
                {
                    key += pi.GetValue(instance, null) + "|";
                }
                if (!keys.Contains(key))
                {
                    keys.Add(key);
                    resultList.Add(instance);
                }
            }
            return resultList;
        }
        public static SqlNetTiersProvider CreateSunProvider(string xmlPath, string connectionName)
        {
            //FileStream reader = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
            string xmlText = File.ReadAllText(xmlPath);
            string decrypt = DecryptData(xmlText);

            XmlDocument xmlDocument = new XmlDocument();// Set up the XmlDocument (CompSpecs) //
            xmlDocument.LoadXml(decrypt); //Load the data from the file into the XmlDocument (CompSpecs) //

            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Server"); // Create a list of the nodes in the xml file //
            string con = "";
            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes["Name"].Value.Equals(connectionName))
                {
                    con = node.Attributes["SunConnectionString"].Value;
                    break;
                }
            }
            if (con != "")
            {
                SqlNetTiersProvider provider = new SqlNetTiersProvider();
                NameValueCollection collection = new NameValueCollection();
                collection.Add("UseStoredProcedure", "false");
                collection.Add("EnableEntityTracking", "true");
                collection.Add("EntityCreationalFactoryType", "Northwind.Entities.EntityFactory");
                collection.Add("EnableMethodAuthorization", "false");
                collection.Add("ConnectionString", con);
                collection.Add("ConnectionStringName", "MyDynamicConnectionString");
                collection.Add("ProviderInvariantName", "System.Data.SqlClient");
                provider.Initialize("DynamicSqlNetTiersProvider", collection);
                return provider;
            }
            return null;
        }
        public static SqlNetTiersProvider CreateProvider(string xmlPath, string connectionName)
        {
            //FileStream reader = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Set up the filestream (READER) //
            string xmlText = File.ReadAllText(xmlPath);
            string decrypt = DecryptData(xmlText);
            XmlDocument xmlDocument = new XmlDocument();// Set up the XmlDocument (CompSpecs) //
            xmlDocument.LoadXml(decrypt); //Load the data from the file into the XmlDocument (CompSpecs) //
            
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Server"); // Create a list of the nodes in the xml file //
            string con = "";
            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes["Name"].Value.Equals(connectionName))
                {
                    con = node.Attributes["ConnectionString"].Value;
                    break;
                }
            }

            if (con != "")
            {
                SqlNetTiersProvider provider = new SqlNetTiersProvider();
                NameValueCollection collection = new NameValueCollection();
                collection.Add("UseStoredProcedure", "false");
                collection.Add("EnableEntityTracking", "true");
                collection.Add("EntityCreationalFactoryType", "Northwind.Entities.EntityFactory");
                collection.Add("EnableMethodAuthorization", "false");
                collection.Add("ConnectionString", con);
                collection.Add("ConnectionStringName", "MyDynamicConnectionString");
                collection.Add("ProviderInvariantName", "System.Data.SqlClient");
                provider.Initialize("DynamicSqlNetTiersProvider", collection);
                return provider;
            }
            return null;
        }

        public static string DecryptData(string cipherText)
        {
            var vector = Encoding.ASCII.GetBytes("aatt1322@#$%asdf");
            var cipher = Convert.FromBase64String(cipherText);
            var key = Encoding.Unicode.GetBytes("_+)&qwer9512popo");
            var sKey = new RijndaelManaged {Mode = CipherMode.CBC};
            var decryptor = sKey.CreateDecryptor(key, vector);
            var memoryStream = new MemoryStream(cipher);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            var plainTextBytes = new byte[cipher.Length];
            var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
            return plainText;
        }

        //public static string Serialize<T>(T value)
        //{

        //    if (value == null)
        //    {
        //        return null;
        //    }

        //    XmlSerializer serializer = new XmlSerializer(typeof(T));

        //    XmlWriterSettings settings = new XmlWriterSettings();
        //    settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string
        //    settings.Indent = false;
        //    settings.OmitXmlDeclaration = false;

        //    using (StringWriter textWriter = new StringWriter())
        //    {
        //        using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
        //        {
        //            serializer.Serialize(xmlWriter, value);
        //        }
        //        return textWriter.ToString();
        //    }
        //}

        //public static T Deserialize<T>(string xml)
        //{

        //    if (string.IsNullOrEmpty(xml))
        //    {
        //        return default(T);
        //    }

        //    XmlSerializer serializer = new XmlSerializer(typeof(T));

        //    XmlReaderSettings settings = new XmlReaderSettings();
        //    // No settings need modifying here

        //    using (StringReader textReader = new StringReader(xml))
        //    {
        //        using (XmlReader xmlReader = XmlReader.Create(textReader, settings))
        //        {
        //            return (T)serializer.Deserialize(xmlReader);
        //        }
        //    }
        //}
    }
}
